﻿using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;
using PmuRegistry.Silverlight.PmuRegistryDataServiceProxy;
using PmuRegistry.Silverlight.Utilities;

namespace PmuRegistry.Silverlight.ModalDialogs
{
	public partial class Phasors : ChildWindow
	{
		int m_sourceDeviceID;
		string m_sourceDeviceAcronym;		
		PhasorDataServiceClient m_client;

		bool inEditMode = false;
		int phasorID = 0;

		public Phasors(int deviceID, string deviceAcronym)
		{
			InitializeComponent();
			m_sourceDeviceID = deviceID;
			m_sourceDeviceAcronym = deviceAcronym;
			this.Title = "Manage Phasors For Device: " + m_sourceDeviceAcronym;
			Loaded += new RoutedEventHandler(Phasors_Loaded);
			ButtonSave.Click += new RoutedEventHandler(ButtonSave_Click);
			ButtonClear.Click += new RoutedEventHandler(ButtonClear_Click);
			m_client = Common.GetPhasorDataServiceClient();
			m_client.GetPhasorListCompleted += new EventHandler<GetPhasorListCompletedEventArgs>(client_GetPhasorListCompleted);
			m_client.GetPhasorsCompleted += new EventHandler<GetPhasorsCompletedEventArgs>(client_GetPhasorsCompleted);
			m_client.SavePhasorCompleted += new EventHandler<SavePhasorCompletedEventArgs>(client_SavePhasorCompleted);
			m_client.GetNetworkModelsCompleted += new EventHandler<GetNetworkModelsCompletedEventArgs>(client_GetNetworkModelsCompleted);
			ListBoxPhasorList.SelectionChanged += new SelectionChangedEventHandler(ListBoxPhasorList_SelectionChanged);
		}

		void client_GetNetworkModelsCompleted(object sender, GetNetworkModelsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxNetworkModelLine.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Network Models", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxNetworkModelLine.Items.Count > 0)
				ComboboxNetworkModelLine.SelectedIndex = 0;
		}

		void client_SavePhasorCompleted(object sender, SavePhasorCompletedEventArgs e)
		{
			SystemMessages sm;
			if (e.Error == null)
			{
				ClearForm();
				sm = new SystemMessages(new Message() { UserMessage = e.Result, SystemMessage = string.Empty, UserMessageType = MessageType.Success },
						ButtonType.OkOnly);
			}
			else
			{
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Save Phasor Information", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
			}
			sm.Show();
			m_client.GetPhasorListAsync(m_sourceDeviceID);
			m_client.GetPhasorsAsync(true);
		}
		
        void client_GetPhasorsCompleted(object sender, GetPhasorsCompletedEventArgs e)
		{
			if (e.Error == null)
				ComboboxDestinationPhasor.ItemsSource = e.Result;				
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Phasors", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
			if (ComboboxDestinationPhasor.Items.Count > 0)
				ComboboxDestinationPhasor.SelectedIndex = 0;
		}
		
        void ListBoxPhasorList_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			if (ListBoxPhasorList.SelectedIndex >= 0)
			{
				Phasor selectedPhasor = ListBoxPhasorList.SelectedItem as Phasor;
				GridPhasorDetail.DataContext = selectedPhasor;
				if (selectedPhasor.DestinationPhasorID.HasValue)
					ComboboxDestinationPhasor.SelectedItem = new KeyValuePair<int, string>((int)selectedPhasor.DestinationPhasorID, selectedPhasor.DestinationPhasorLabel);
				else
					ComboboxDestinationPhasor.SelectedIndex = 0;
				if (selectedPhasor.NetworkModelID.HasValue)
					ComboboxNetworkModelLine.SelectedItem = new KeyValuePair<int, string>((int)selectedPhasor.NetworkModelID, selectedPhasor.NetworkElementUID);
				else
					ComboboxNetworkModelLine.SelectedIndex = 0;
				ComboboxPhase.SelectedItem = new KeyValuePair<string, string>(selectedPhasor.Phase, selectedPhasor.PhaseType);
				ComboboxType.SelectedItem = new KeyValuePair<string, string>(selectedPhasor.Type, selectedPhasor.PhasorType);

				inEditMode = true;
				phasorID = selectedPhasor.ID;
			}
		}
		
        void client_GetPhasorListCompleted(object sender, GetPhasorListCompletedEventArgs e)
		{
			if (e.Error == null)
				ListBoxPhasorList.ItemsSource = e.Result;
			else
			{
				SystemMessages sm;
				if (e.Error is FaultException<CustomServiceFault>)
				{
					FaultException<CustomServiceFault> fault = e.Error as FaultException<CustomServiceFault>;
					sm = new SystemMessages(new Message() { UserMessage = fault.Detail.UserMessage, SystemMessage = fault.Detail.SystemMessage, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);
				}
				else
					sm = new SystemMessages(new Message() { UserMessage = "Failed to Retrieve Phasor List", SystemMessage = e.Error.Message, UserMessageType = MessageType.Error },
						ButtonType.OkOnly);

				sm.Show();
			}
		}
		
        void ButtonClear_Click(object sender, RoutedEventArgs e)
		{
			Storyboard sb = new Storyboard();
			sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
			sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
			Storyboard.SetTarget(sb, ButtonClearTransform);
			sb.Begin();
			ClearForm();
		}

        void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            Storyboard sb = new Storyboard();
            sb = Application.Current.Resources["ButtonPressAnimation"] as Storyboard;
            sb.Completed += new EventHandler(delegate(object obj, EventArgs es) { sb.Stop(); });
            Storyboard.SetTarget(sb, ButtonSaveTransform);
            sb.Begin();

            if (IsValid())
            {
                Phasor phasor = new Phasor();
                phasor.DeviceID = m_sourceDeviceID;
                phasor.Label = TextBoxLabel.Text.CleanText();
                phasor.Type = ((KeyValuePair<string, string>)ComboboxType.SelectedItem).Key;
                phasor.Phase = ((KeyValuePair<string, string>)ComboboxPhase.SelectedItem).Key;
                phasor.DestinationPhasorID = ((KeyValuePair<int, string>)ComboboxDestinationPhasor.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboboxDestinationPhasor.SelectedItem).Key;
                phasor.SourceIndex = TextBoxSourceIndex.Text.ToInteger();
                phasor.NetworkModelID = ((KeyValuePair<int, string>)ComboboxNetworkModelLine.SelectedItem).Key == 0 ? (int?)null : ((KeyValuePair<int, string>)ComboboxNetworkModelLine.SelectedItem).Key;

                if (inEditMode == true && phasorID > 0)
                {
                    phasor.ID = phasorID;
                    m_client.SavePhasorAsync(phasor, false);
                }
                else
                    m_client.SavePhasorAsync(phasor, true);
            }
        }

        bool IsValid()
        {
            bool isValid = true;

            if (string.IsNullOrEmpty(TextBoxLabel.Text.CleanText()))
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Phasor Label", SystemMessage = "Please provide valid phasor Label.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxLabel.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            if (!TextBoxSourceIndex.Text.IsInteger())
            {
                isValid = false;
                SystemMessages sm = new SystemMessages(new Message() { UserMessage = "Invalid Phasor Source Index", SystemMessage = "Please provide valid integer value for Phasor Source Index.", UserMessageType = MessageType.Error },
                        ButtonType.OkOnly);
                sm.Closed += new EventHandler(delegate(object sender, EventArgs e)
                                                {
                                                    TextBoxSourceIndex.Focus();
                                                });
                sm.Show();
                return isValid;
            }

            return isValid;
        }

        void Phasors_Loaded(object sender, RoutedEventArgs e)
		{
			m_client.GetPhasorListAsync(m_sourceDeviceID);
			m_client.GetPhasorsAsync(true);
			m_client.GetNetworkModelsAsync(true);
			ComboboxPhase.Items.Add(new KeyValuePair<string, string>("+", "Positive"));
			ComboboxPhase.Items.Add(new KeyValuePair<string, string>("-", "Negative"));
			ComboboxPhase.Items.Add(new KeyValuePair<string, string>("A", "Phase A"));
			ComboboxPhase.Items.Add(new KeyValuePair<string, string>("B", "Phase B"));
			ComboboxPhase.Items.Add(new KeyValuePair<string, string>("C", "Phase C"));
			ComboboxPhase.SelectedIndex = 0;

			ComboboxType.Items.Add(new KeyValuePair<string, string>("V", "Voltage"));
			ComboboxType.Items.Add(new KeyValuePair<string, string>("I", "Current"));
			ComboboxType.SelectedIndex = 0;
		}
		
        void ClearForm()
		{
			GridPhasorDetail.DataContext = new Phasor();
			ComboboxPhase.SelectedIndex = 0;
			ComboboxType.SelectedIndex = 0;
			ComboboxDestinationPhasor.SelectedIndex = 0;
			ComboboxNetworkModelLine.SelectedIndex = 0;
			ListBoxPhasorList.SelectedIndex = -1;
			inEditMode = false;
			phasorID = 0;
		}

	}
}

